import { createRouter, createWebHistory } from 'vue-router';
import useUserStore from '@/stores/user';
import useRouterStore from '@/stores/router';

const routes = [
  {
    path: '/',
    title: '首页',
    name: 'layout',
    component: () => import('@/views/layout/index.vue'),
    children: [
      {
        path: '/',
        name: 'workBench',
        meta: {
          title: '工作台'
        },
        component: () => import('@/views/workbench/index.vue')
      }
    ]
  },
  {
    path: '/login',
    name: 'workBenchLogin',
    meta: {
      title: '登录'
    },
    component: () => import('@/views/workbench/login.vue')
  },
  {
    path: '/log/test',
    name: 'test1',

    component: () => import('@/views/log/test.vue')
  },
  {
    path: '/log/test2',
    name: 'test2',

    component: () => import('@/views/log/test.vue')
  },

  {
    path: '/:error*',
    name: '404',
    component: () => import('@/views/error/404.vue')
  }
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
});

router.beforeEach(async (to, from, next) => {
  const { token } = useUserStore();
  if (token) {
    const routerStore = useRouterStore();
    if (routerStore.routerList.length) {
      next();
    } else {
      const result = await routerStore.generateRouter();
      result ? next(to.fullPath) : next();
    }
  } else {
    if (to.path === '/login') {
      next();
    } else {
      const query = {};
      if (to.fullPath !== '/') {
        query.redirect = to.fullPath;
      }
      next({ path: '/login', query, replace: true });
    }
  }
});

export default router;
